package com.hovhanna.monopoly.common;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Event {
    private ReentrantLock lock;
    private Condition condition = lock.newCondition();
    private volatile boolean signaled;
    
    public boolean waitForEvent(long timeout) {
        boolean signaled = this.signaled;
        if (!signaled) {
            try {
                lock.lock();
                signaled = condition.await(timeout, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
            } finally {
                this.signaled = false;
                if (lock.isLocked()) {
                    lock.unlock();
                }
            }
        }
        return signaled;
    }
    
    public void setEvent() {
        try {
            lock.lock();
            signaled = true;
            condition.signal();
        } finally {
            if (lock.isLocked()) {
                lock.unlock();
            }
        }
    }
}
